/**
 * @create 2022-04-07
 * @desc table
 */

import type { TableColumnType, PaginationProps } from 'antd';
import { Table } from 'antd';
import { useMemo } from 'react';
import { useMemoizedFn } from 'ahooks';
import { useData } from '../../hooks/use-data';
import { useProTableStore, useProTableStoreDispatch } from '../../context/store';
import type { TableProProps } from './interface';

export const TableComp = <T extends Record<string, any>>(props: TableProProps<T>) => {
  const { columns, pagination: paginationProps, ...rest } = props;
  const { pagination: paginationContext } = useProTableStore();
  const storeDispatch = useProTableStoreDispatch();
  const { data, loading } = useData<T>();

  const paginationChange = useMemoizedFn((current: number, pageSize: number) => {
    storeDispatch({
      type: 'onPaginationChange',
      payload: { current, pageSize },
    });
    if (typeof paginationProps === 'object') {
      paginationProps.onChange?.(current, pageSize);
    }
  });
  const paginationData = useMemo<PaginationProps | false>(() => {
    return paginationProps === false
      ? paginationProps
      : {
          ...paginationContext,
          ...paginationProps,
          total: data?.total,
          onChange: paginationChange,
        };
  }, [paginationProps, paginationContext, data?.total, paginationChange]);

  const newColumns = columns.map((item) => {
    return { ellipsis: true, ...item };
  }) as TableColumnType<T>[];

  return (
    <Table<T>
      columns={newColumns}
      {...rest}
      pagination={paginationData}
      loading={loading}
      dataSource={data?.data}
    />
  );
};
